'use client'

import { useState } from 'react';
import Box from '@mui/material/Box';
import ListItem from '@mui/material/ListItem';
import ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';
import Collapse from '@mui/material/Collapse';
import Divider from '@mui/material/Divider';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import List from '@mui/material/List';

const get_icon = (icon) => {
    if (icon) {
        return (
            <ListItemIcon>
                {icon}
            </ListItemIcon>
        )
    }

    return null;
};

/* list: [{sn: "xx", name: "xx"}]
*/
const GListSub = ({ label, select, hselect, list, icon }) => {
    const [open, setOpen] = useState(false);

    const getList = () => {
        if (!list) {
            return null;
        }

        return list.map(d => {
            if (d.tp === "div") {
                return <GListItem tp="div" key={d.sn}/>;
            }
            else {
                return (
                    <ListItemButton sx={{ pl: 6 }} selected={select === d.sn} onClick={() => hselect(d.sn)} key={d.sn}>
                        <ListItemText primary={d.name} secondary={d.sub}/>
                    </ListItemButton>
                );
            }
        });
    };

    return (
        <>
            <ListItemButton onClick={() => setOpen(!open)}>
                {get_icon(icon)}
                <ListItemText primary={label} />
                {open ? <ExpandLess /> : <ExpandMore />}
            </ListItemButton>
            <Collapse in={open} timeout="auto" unmountOnExit>
                <List component="div" disablePadding>
                    {getList()}
                </List>
            </Collapse>
        </>
    );
}

/* item: {sn: "xx", name: "xx"}
*/
const GListItem = ({ select, hselect, item, icon, tp="item", children, width=250 }) => {
    if (tp === "div") {
        return <Divider/>;
    }

    if (tp === "top") {
        return (
            <Box sx={{ width: width }} role="presentation">
                <List>
                    {children}
                </List>
            </Box>
        );
    }

    return (
        <ListItem disablePadding>
            <ListItemButton selected={select === item.sn} onClick={() => hselect(item.sn)}>
                {get_icon(icon)}
                <ListItemText primary={item.name} secondary={item.sub}/>
            </ListItemButton>
        </ListItem>
    );
}

export {GListItem, GListSub};
